<?

class bf_sql_model extends bf_model {

	protected function sql_count($sql_filters) {
		return 'select 0';
	}

	protected function sql_select($sql_filters) {
		return 'select 0 where ' . $this->db->get_false();
	}

	// in: $filters, $params
	// out: $params, $sql_filters
	protected function sql_filters($filters, &$params, &$sql_filters) {
//		// example
//		if (isset($filters['id']) && $filters['id']) {
//			$params[] = $filters['id'];
//			$p = '$' . count($params);
//			$sql_filters[] = 'users.id = ' . $p;
//		}
	}

	protected function build_filters($filters = array(), $params = array()) {

		$sql_filters = array();
		$this->sql_filters($filters, $params, $sql_filters);
		if (count($sql_filters)) {
			$sql_filters = '' . implode(' and ', $sql_filters);
		} else {
			$sql_filters = $this->db->get_true();
		}
		
		return (object) array(
			'filters' => $sql_filters,
			'params' => $params
		);
	}

	protected function post_process($row) {
		return $row;
	}

	public function count($filters = array()) {
		$f = $this->build_filters($filters);
		return $this->db->query_column($this->sql_count($f->filters), $f->params);
	}

	public function select($filters = array(), $offset = 0, $limit = null) {
		$f = $this->build_filters($filters, array($offset, $limit));
	        $res = array();
		foreach ($this->db->query_all_obj($this->sql_select($f->filters), $f->params) as $row) {
			$res[] = $this->post_process($row);
		}
		return $res;
	}

	public function get($id) {
		if (!$id) {
			return null;
		}
		$rows = $this->select(array('id' => $id), 0, 1);
		return (count($rows) > 0 ? $rows[0] : null);
	}
}

?>